<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script>
    <title>HTML to Image</title>
  </head>
  <body>
    <div
      id="capture"
      style="width: 300px; height: 300px; background-color: lightblue"
    >
      <h2>Hello, World!</h2>
      <p>This is a test for converting HTML to an image.</p>
      <div class="likeAvatar squareImage" style="background-image:url(./src/stable/-1mM6wkbPbdg9c_1.jpg)">
      </div>
      <div class="likeAvatar squareImage" style="background-image:url(./src/stable/-1mM6wkbPbdg9c_1.jpg)">
      </div>
    <button id="saveImage">Save as Image</button>
    <style>
      .squareImage {
        background-size: cover;
        background-position: center center;
        background-repeat: no-repeat;
      }
      .likeAvatar {
        width: 84px;
        height: 84px;
        margin: 17px 17px 0 0;
        display: inline-block;
      }
    </style>
    <script>
      document.getElementById("saveImage").addEventListener("click", async function () {
        const element = document.getElementById("capture");
        // 找到所有的图片
        const images = element.querySelectorAll("img");
        const imageLoadPromises = Array.from(images).map((img) => {
          if (img.complete) {
            return Promise.resolve(); // 如果图片已经加载完成
          }
          return new Promise((resolve, reject) => {
            img.onload = resolve;
            img.onerror = reject;
          });
      });

      try {
        // 等待所有图片加载完成
        await Promise.all(imageLoadPromises);

        // 使用 html2canvas 转换
        html2canvas(element).then((canvas) => {
          const link = document.createElement("a");
          link.href = canvas.toDataURL("image/png");
          link.download = "screenshot.png";
          link.click();
        });
      } catch (error) {
          console.error("图片加载失败：", error);
        }
      });

    </script>
  </body>
</html>
